~ chicken-core (master) /manual/Getting started


  1[[tags: manual]]
  2
  3== Getting started
  4
  5CHICKEN is a compiler that translates Scheme source files into
  6C, which in turn can be fed to a C compiler to generate a
  7standalone executable.  An interpreter is also available and can be
  8used as a scripting environment or for testing programs before
  9compilation.
 10
 11This chapter is designed to get you started with CHICKEN programming,
 12describing what it is and what it will do for you, and covering basic
 13use of the system. With almost everything discussed here, there is
 14more to the story, which the remainder of the manual reveals. Here, we
 15only cover enough to get you started. Nonetheless, someone who knows
 16Scheme already should be able to use this chapter as the basis for
 17writing and running small CHICKEN programs.
 18
 19=== Scheme
 20
 21Scheme is a member of the Lisp family of languages, of which Common
 22Lisp, Emacs Lisp and Clojure are other widely-known members. As with
 23Lisp dialects, Scheme features
 24
 25* a wide variety of programming paradigms, including imperative, functional, and object-oriented
 26* a very simple syntax, based upon nested parenthesization
 27* the ability to extend the language in meaningful and useful ways
 28
 29In contrast to Common Lisp, Scheme is very minimal, and tries to
 30include only those features absolutely necessary in programming. In
 31contrast to Emacs Lisp, Scheme is not anchored into a single program
 32(Emacs), and has a more modern and elegant language design. In contrast
 33to Clojure, Scheme provides only a very minimal set of concepts but allows
 34them to be used in very general ways with few restrictions.
 35
 36Scheme is defined in a document called ''The Revised^7 Report on the
 37Algorithmic Language Scheme'', or ''R7RS'' for short. (Yes, it really
 38has been revised seven times, so an expanded version of its name would
 39be ''The Revised Revised Revised Revised Revised Report''.)
 40
 41CHICKEN fully complies with R7RS.
 42
 43Even though Scheme is consciously minimalist, it is recognized that a
 44language must be more than a minimal core in order to be
 45useful. Accordingly, the Scheme community uses a process known as
 46`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to
 47define new language features. A typical Scheme system therefore
 48complies with one of the Scheme reports plus some or all of the
 49accepted SRFIs.
 50
 51A good starting point for Scheme knowledge is
 52[[http://www.schemers.org]]. There you will find the defining reports,
 53FAQs, lists of useful books and other resources, and the SRFIs.
 54
 55=== CHICKEN
 56
 57CHICKEN Scheme combines an optimising compiler with a reasonably fast
 58interpreter.  It supports all of R7RS and the important SRFIs.
 59The compiler generates portable C code that supports tail recursion,
 60first-class continuations and lightweight threads, and the interface to
 61and from C libraries is flexible, efficient, and easy to use.  There are
 62hundreds of contributed CHICKEN libraries that make the programmer's
 63task easier.  The interpreter allows interactive use, fast prototyping,
 64debugging, and scripting.  The active and helpful CHICKEN community
 65fixes bugs and provides support.  Extensive documentation is supplied.
 66
 67CHICKEN was developed by Felix L. Winkelmann over the period from 2000
 68through 2007. In early 2008, Felix
 69asked the community to take over the responsibility of developing and
 70maintaining the system, though he still takes a strong interest in it,
 71and participates actively.
 72
 73CHICKEN includes
 74
 75* a Scheme interpreter that supports all of R7RS Scheme, with
 76  only a few relatively minor omissions, and with many extensions
 77* a compatible compiler whose target is C, thus making porting to new
 78  machines and architectures relatively straightforward
 79* the C support allows Scheme code to include `embedded' C code,
 80  thus making it easy to invoke host OS or library
 81  functions
 82* a framework for language extensions, library modules that broaden
 83  the functionality of the system
 84
 85This package is distributed under the '''BSD license''' and as such is free
 86to use and modify as long as the original authors are acknowledged.
 87
 88Scheme cognoscenti will appreciate the method of compilation and the
 89design of the runtime-system, which follow closely Henry Baker's
 90[[https://web.archive.org/web/20200223051632/http://home.pipeline.com/~hbaker1/CheneyMTA.html|CONS Should Not
 91CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a
 92number of interesting properties.
 93
 94* Consing (creation of data on the heap) is inexpensive,
 95  because a generational garbage collection scheme is used in combination
 96  with allocating on the C stack, in which short-lived data structures are reclaimed
 97  extremely quickly.
 98
 99* Moreover, {{call-with-current-continuation}} involves only minimal
100  overhead and CHICKEN does not suffer under any performance penalties if
101  first-class continuations are used in complex ways.
102
103The generated C code fully supports tail-call optimization (TCO).
104
105Some of the features supported by CHICKEN:
106
107* Lightweight threads based on first-class continuations
108* Record structures
109* Extended comment- and string-literal syntaxes
110* Libraries for regular expressions, string handling
111* UNIX system calls and extended data structures
112* Compiled C files can be easily distributed
113* Allows the creation of fully self-contained statically linked executables
114* On systems that support it, compiled code can be loaded dynamically
115* Built-in support for cross-compilation
116
117CHICKEN has been used in many environments ranging from embedded
118systems through desktop machines to large-scale server deployments.
119The number of language extensions, or '''eggs''', is constantly growing:
120
121* extended language features
122* development tools, such as documentation generators, debugging, and
123  automated testing libraries
124* interfaces to other languages such as Java, Python, and Objective-C
125* interfaces to database systems, GUIs, and other libraries,
126* network applications, such as servers and clients for ftp,
127  smtp/pop3, irc, and http
128* web servers and related tools, including URL parsing, HTML
129  generation, AJAX, and HTTP session management
130* data formats, including XML, JSON, and Unicode support
131
132This chapter provides you with an overview of the entire system, with
133enough information to get started writing and running small Scheme
134programs.
135
136=== CHICKEN repositories, websites and community
137
138The master CHICKEN website is
139[[http://www.call-cc.org]]. Here you can find
140basic information about CHICKEN, downloads and pointers to other key
141resources.
142
143The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most
144current version of the User's manual, along with various tutorials and
145other useful documents. The list of eggs is at
146[[http://wiki.call-cc.org/egg-index|http://wiki.call-cc.org/egg-index]].
147
148A very useful search facility for questions about procedures and syntax
149available for CHICKEN can be found at
150[[http://api.call-cc.org]]. The CHICKEN issue tracker is at
151[[http://bugs.call-cc.org]].
152
153The CHICKEN community has two major mailing lists. If you are a
154CHICKEN user, {{chicken-users}}
155([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be
156of interest. The crew working on the CHICKEN system itself uses the
157very low-volume {{chicken-hackers}} list
158([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for
159communication.  For other topic-specific mailing lists (e.g.,
160announcements, security) and discussion groups, see
161[[http://wiki.call-cc.org/discussion-groups|http://wiki.call-cc.org/discussion-groups]].
162
163There is also an IRC channel ({{#chicken}}) on
164[[http://libera.chat|Libera.Chat]].
165
166=== Installing CHICKEN
167
168CHICKEN is available as C sources. Refer to the
169{{README}} file in the distribution for instructions on installing it
170on your system.
171
172Because it compiles to C, CHICKEN requires that a C compiler be
173installed on your system. (If you're not writing embedded C code, you
174can pretty much ignore the C compiler once you have installed it.)
175
176* On a Linux system, a C toolchain (e.g., GCC, clang) should be
177  installed as part of the basic operating system, or should be
178  available through the package management system (e.g., APT,
179  Synaptic, RPM, or Yum, depending upon your Linux distribution).
180* On Macintosh OS X, you will need the XCode tools, which are
181  installable from the App Store.
182* On Windows, you have two choices:
183* Cygwin ([[https://www.cygwin.com/]]) provides a relatively
184  full-featured Unix environment for Windows.  CHICKEN works
185  substantially the same in Cygwin and Unix.
186* The GNU Compiler Collection has been ported to Windows, in the
187  MinGW system. Unlike Cygwin,
188  executables produced with MinGW do not need the Cygwin DLLs in order
189  to run.
190
191Refer to the {{README}} file for the version you're installing for
192more information on the installation process.
193
194Alternatively, third party packages in binary format are
195available. See
196[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]
197for information about how to obtain them.
198
199=== Development environments
200
201The simplest development environment is a text editor and terminal
202window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for
203using the interpreter and/or invoking the compiler.  If you install one
204of the line editing extensions (e.g., [[/egg/breadline|breadline]], [[/egg/linenoise|linenoise]]), you have some
205useful command line editing features in the interpreter (e.g., Emacs
206or vi-compatible line editing, customization).
207
208It will be helpful to use a text editor that knows Scheme; it can be painful
209with editors that don't do parenthesis matching and automatic
210indentation.
211
212In the rest of this chapter, we'll assume that you are using an editor
213of your choice and a regular terminal window for executing your
214CHICKEN code.
215
216=== The Read-Eval-Print loop
217
218To invoke the CHICKEN interpreter, you use the {{csi}} command.
219
220 $ csi
221 CHICKEN
222 (c) 2008-2021, The CHICKEN Team
223 (c) 2000-2007, Felix L. Winkelmann
224 Version 5.3.0 (rev e31bbee5)
225 linux-unix-gnu-x86-64 [ 64bit dload ptables ]
226
227 Type ,? for help.
228 #;1>
229
230This brings up a brief banner, and then the prompt. You can use this
231pretty much like any other Scheme system, e.g.,
232
233 #;1> (define (twice f) (lambda (x) (f (f x))))
234 #;2> ((twice (lambda (n) (* n 10))) 3)
235 300
236
237Suppose  we have already created a file {{fact.scm}} containing a
238function definition.
239
240 (define (fact n)
241   (if (= n 0)
242       1
243       (* n (fact (- n 1)))))
244
245We can now load this file and try out the function.
246
247 #;3> (load "fact.scm")
248 ; loading fact.scm ...
249 #;4> (fact 3)
250 6
251
252The '''read-eval-print loop''' ('''REPL''') is the component of the
253Scheme system that ''reads'' a Scheme expression, ''eval''uates it,
254and ''prints'' out the result. The REPL's prompt can be customized
255(see the [[Using the interpreter]])
256but the default prompt, showing the number of the form, is quite
257convenient.
258
259The REPL also supports debugging commands:
260input lines beginning with a {{,}} (comma) are treated as special
261commands. (See the [[Using the interpreter#Toplevel commands|full list]].)
262
263
264==== Scripts
265
266You can use the interpreter to run a Scheme program from the command
267line. For the following example we create a program that does a quick
268search-and-replace on an input file; the arguments are a regular
269expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:
270
271 xyzabcghi
272 abxawxcgh
273 foonly
274
275Next create the scheme code in a file called ''quickrep.scm'' with the
276following little program:
277
278<enscript highlight=scheme>
279;; irregex, the regular expression library, is one of the
280;; libraries included with CHICKEN.
281(import (chicken irregex)
282        (chicken io))
283
284(define (process-line line re rplc)
285  (irregex-replace/all re line rplc))
286
287(define (quickrep re rplc)
288  (let ((line (read-line)))
289    (if (not (eof-object? line))
290        (begin
291          (display (process-line line re rplc))
292          (newline)
293          (quickrep re rplc)))))
294
295;;; Does a lousy job of error checking!
296(define (main args)
297  (quickrep (irregex (car args)) (cadr args)))
298</enscript>
299
300
301To run it enter this in your shell:
302
303 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A
304 xyzAghi
305 Agh
306 foonly
307
308The {{-ss}} option sets several options that work smoothly together to
309execute a script. You can make the command directly executable from
310the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]
311at the beginning of the program.
312
313The {{-ss}} option arranges to call a procedure named {{main}}, with
314the command line arguments, packed in a list, as its arguments. (There
315are a number of ways this program could be made more idiomatic CHICKEN
316Scheme, see the rest of the manual for details.)
317
318=== The compiler
319
320There are several reasons you might want to compile your code.
321
322* Compiled code executes substantially faster than interpreted
323  code.
324* You might want to deploy an application onto machines where the
325  users aren't expected to have CHICKEN installed: compiled
326  applications can be self-contained.
327* Compiled code can access external libraries written in lower-level
328  languages that follow the C calling convention.
329
330The CHICKEN compiler is provided as the command {{chicken}}, but in
331almost all cases, you will want to use the {{csc}} command
332instead. {{csc}} is a convenient driver that automates compiling
333Scheme programs into C, compiling C code into object code, and linking
334the results into an executable file. (Note: in a Windows environment
335with Visual Studio, you may find that {{csc}} refers to Microsoft's
336C# compiler. There are a number of ways of sorting this out, of which
337the simplest is to rename one of the two tools, and/or to
338organize your {{PATH}} according to the task at hand.)
339
340We can compile our factorial function, producing a file named
341{{fact.so}} (''shared object'' in Linux-ese, the same file extension is
342used in Windows, rather than {{dll}})
343
344 chicken$ csc -shared fact.scm
345 chicken$ csi -quiet
346 #;1> (load "fact.so")
347 ; loading fact.so ...
348 #;2> (fact 6)
349 720
350
351On any system, we can just compile a program directly into an
352executable. Here's a program that tells you whether its argument is a
353palindrome.
354
355<enscript highlight=scheme>
356(import (chicken process-context)) ; for "command-line-arguments"
357
358(define (palindrome? x)
359  (define (check left right)
360    (if (>= left right)
361        #t
362        (and (char=? (string-ref x left) (string-ref x right))
363             (check (add1 left) (sub1 right)))))
364  (check 0 (sub1 (string-length x))))
365
366(let ((arg (car (command-line-arguments))))
367  (display
368   (string-append arg
369                  (if (palindrome? arg)
370                      " is a palindrome\n"
371                      " isn't a palindrome\n"))))
372</enscript>
373
374We can compile this program using {{csc}}, creating an executable
375named {{palindrome}}.
376
377 $ csc -o palindrome palindrome.scm
378 $ ./palindrome level
379 level is a palindrome
380 $ ./palindrome liver
381 liver isn't a palindrome
382
383CHICKEN supports separate compilation, using some extensions to
384Scheme. Let's divide our palindrome program into a library module
385({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).
386
387Here's the external library. We {{declare}} that {{pal-proc}} is a
388''unit'', which is the basis of separately-compiled modules in
389CHICKEN. (Units deal with separate compilation, but don't necessarily
390involve separated namespaces; namespaces can be implemented by
391[[/manual/Modules|modules]].)
392
393<enscript highlight=scheme>
394;;; Library pal-proc.scm
395(declare (unit pal-proc))
396
397(define (palindrome? x)
398  (define (check left right)
399    (if (>= left right)
400        #t
401        (and (char=? (string-ref x left) (string-ref x right))
402             (check (add1 left) (sub1 right)))))
403  (check 0 (sub1 (string-length x))))
404</enscript>
405
406Next we have some  client code that ''uses'' this separately-compiled
407module.
408
409<enscript highlight=scheme>
410;;; Client pal-user.scm
411(declare (uses pal-proc))
412
413(import (chicken process-context))
414
415(let ((arg (car (command-line-arguments))))
416  (display
417   (string-append arg
418                  (if (palindrome? arg)
419                      " is a palindrome\n"
420                      " isn't a palindrome\n"))))
421</enscript>
422
423Now we can compile and link everything together. (We show the compile
424and link operations separately, but they can of course be combined
425into one command.)
426
427 $ csc -c pal-proc.scm
428 $ csc -c pal-user.scm
429 $ csc -o pal-separate pal-proc.o pal-user.o
430 $ ./pal-separate level
431 level is a palindrome
432
433The "unit" mechanism is relatively low-level and requires some
434familiarity with underlying mechanism used to manage compilation
435units. See [[Units and linking model]] for more information.
436
437=== Installing an egg
438
439Installing eggs is quite straightforward on systems that support
440dynamic loading (that would include *BSD, Linux, Mac OS X,
441Solaris, and Windows).  The command {{chicken-install}} will fetch an
442egg from the master CHICKEN repository, and install it on your local
443system.
444
445In this example, we install the {{uri-common}} egg, for parsing
446Uniform Resource Identifiers.
447
448 $ chicken-install uri-common
449
450{{chicken-install}} connects to a mirror of the egg repository and
451retrieves the egg contents.  If the egg has any uninstalled
452dependencies, it recursively installs them.  Then it builds the egg
453code and installs the resulting extension into the
454local CHICKEN repository.
455
456Now we can use our new egg.
457
458 #;1> (import uri-common)
459 ; loading /usr/lib/chicken/9/uri-common.import.so ...
460 ; [... other loaded files omitted for clarity ...]
461
462 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))
463 "www.foobar.org"
464
465=== Accessing C libraries
466
467Because CHICKEN compiles to C, and because a foreign function
468interface is built into the compiler, interfacing to a C library is
469quite straightforward. This means that any facility available
470on the host system is accessible from CHICKEN, with more or less
471work.
472
473Let's create a simple C library, to demonstrate how this
474works. Here we have a function that will compute and return the '''n'''th
475Fibonacci number. (This isn't a particularly good use of C here,
476because we could write this function just as easily in Scheme, but a
477real example would take far too much space here.)
478
479 /* fib.c */
480 int fib(int n) {
481   int prev = 0, curr = 1;
482   int next;
483   int i;
484   for (i = 0; i < n; i++) {
485     next = prev + curr;
486     prev = curr;
487     curr = next;
488   }
489   return curr;
490 }
491
492Now we can call this function from CHICKEN.
493
494 ;;; fib-user.scm
495 (import (chicken foreign) (chicken format))
496
497 #>
498   extern int fib(int n);
499 <#
500 (define xfib (foreign-lambda int "fib" int))
501 (do ((i 0 (+ i 1))) ((> i 10))
502   (printf "~A " (xfib i)))
503 (newline)
504
505The syntax {{#>...<#}} allows you to include literal C (typically
506external declarations) in your CHICKEN code. We access {{fib}} by
507defining a {{foreign-lambda}} for it, in this case saying that the
508function takes one integer argument (the {{int}} after the function
509name), and that it returns an integer result (the {{int}} before.) Now we can invoke
510{{xfib}} as though it were an ordinary Scheme function.
511
512 $ gcc -c fib.c
513 $ csc -o fib-user fib.o fib-user.scm
514
515If using MinGW on Windows,
516
517 > gcc -c fib.c -o fib.obj
518 > csc -o fib-user fib.obj fib-user.scm
519
520Then run the executable.
521 $ ./fib-user
522 0 1 1 2 3 5 8 13 21 34 55
523
524Those who are interfacing to substantial C libraries should consider
525using the [[/egg/bind|bind egg]].
526
527---
528
529Back to [[The User's Manual]]
530
531Next: [[Using the interpreter]]
Trap